import Gift from './sequelize/Gift';
import UserRoomGift from './sequelize/UserRoomGift';
import { v4 as uuidv4 } from 'uuid';

export class GiftService {
  /**
   * 创建礼物
   * @param giftData 礼物数据
   */
  async createGift(giftData: {
    name: string;
    price: number;
    type?: number;
    description?: string;
    icon?: string;
  }) {
    try {
      const gift = await Gift.create({
        id: uuidv4(),
        ...giftData
      });
      console.log(`🎁 创建礼物成功: ${gift.name}`);
      return gift;
    } catch (error) {
      console.error('❌ 创建礼物失败:', error);
      throw error;
    }
  }

  /**
   * 根据名称获取礼物
   * @param name 礼物名称
   */
  async getGiftByName(name: string) {
    try {
      return await Gift.findOne({ where: { name } });
    } catch (error) {
      console.error('❌ 获取礼物失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID获取礼物
   * @param id 礼物ID
   */
  async getGiftById(id: string) {
    try {
      return await Gift.findByPk(id);
    } catch (error) {
      console.error('❌ 获取礼物失败:', error);
      throw error;
    }
  }

  /**
   * 获取所有礼物
   * @param options 查询选项
   */
  async getAllGifts(options: {
    limit?: number;
    offset?: number;
  } = {}) {
    try {
      const { limit, offset } = options;

      return await Gift.findAll({
        order: [['name', 'ASC']],
        limit,
        offset
      });
    } catch (error) {
      console.error('❌ 获取礼物列表失败:', error);
      throw error;
    }
  }

  /**
   * 更新礼物信息
   * @param id 礼物ID
   * @param updateData 更新数据
   */
  async updateGift(id: string, updateData: {
    name?: string;
    price?: number;
    type?: number;
    description?: string;
    icon?: string;
  }) {
    try {
      const [affectedRows] = await Gift.update(updateData, {
        where: { id }
      });
      
      if (affectedRows > 0) {
        console.log(`🎁 更新礼物成功: ${id}`);
        return await this.getGiftById(id);
      } else {
        throw new Error('礼物不存在');
      }
    } catch (error) {
      console.error('❌ 更新礼物失败:', error);
      throw error;
    }
  }

  /**
   * 删除礼物
   * @param id 礼物ID
   */
  async deleteGift(id: string) {
    try {
      const affectedRows = await Gift.destroy({
        where: { id }
      });
      
      if (affectedRows > 0) {
        console.log(`🎁 删除礼物成功: ${id}`);
        return true;
      } else {
        throw new Error('礼物不存在');
      }
    } catch (error) {
      console.error('❌ 删除礼物失败:', error);
      throw error;
    }
  }

  /**
   * 获取或创建礼物（用于处理直播消息中的礼物）
   * @param giftData 礼物数据
   */
  async getOrCreateGift(giftData: {
    name: string;
    price: number;
    type?: number;
    description?: string;
    icon?: string;
  }) {
    try {
      let gift = await this.getGiftByName(giftData.name);
      
      if (!gift) {
        gift = await this.createGift(giftData);
      }
      
      return gift;
    } catch (error) {
      console.error('❌ 获取或创建礼物失败:', error);
      throw error;
    }
  }

  /**
   * 获取礼物统计信息
   */
  async getGiftStats() {
    try {
      const totalCount = await Gift.count();
      
      return {
        totalCount
      };
    } catch (error) {
      console.error('❌ 获取礼物统计失败:', error);
      throw error;
    }
  }

  async getSessionGiftSummary(sessionId: string) {
    try {
      if (!sessionId) {
        return {
          totalRecords: 0,
          totalQuantity: 0,
          totalGiftTypes: 0,
          totalSoundWave: 0,
          uniqueUsers: 0,
          breakdown: [] as Array<{
            giftId: string | null;
            name: string;
            quantity: number;
            price: number;
            amount: number;
            icon?: string | null;
            type?: number | null;
          }>,
        };
      }

      const giftRecords = await UserRoomGift.findAll({
        where: { sessionId },
        include: [
          {
            model: Gift,
            as: 'gift',
            attributes: ['id', 'name', 'price', 'icon', 'type'],
          },
        ],
        attributes: ['id', 'giftId', 'quantity', 'userId', 'createdAt'],
        order: [['createdAt', 'ASC']],
      });

      if (giftRecords.length === 0) {
        return {
          totalRecords: 0,
          totalQuantity: 0,
          totalGiftTypes: 0,
          totalSoundWave: 0,
          uniqueUsers: 0,
          breakdown: [] as Array<{
            giftId: string | null;
            name: string;
            quantity: number;
            price: number;
            amount: number;
            icon?: string | null;
            type?: number | null;
          }>,
        };
      }

      let totalQuantity = 0;
      let totalSoundWave = 0;
      const uniqueUsers = new Set<string>();
      const breakdownMap = new Map<string, {
        giftId: string | null;
        name: string;
        quantity: number;
        price: number;
        amount: number;
        icon?: string | null;
        type?: number | null;
      }>();

      for (const record of giftRecords) {
        const quantity = Number(record.get('quantity')) || 0;
        const userId = record.get('userId') as string | undefined;
        if (userId) {
          uniqueUsers.add(userId);
        }

        const giftModel = record.get('gift') as Gift | null;
        const price = giftModel?.get('price');
        const numericPrice = typeof price === 'number' ? price : Number(price) || 0;
        const typeValue = giftModel?.get('type');
        const normalizedType = typeof typeValue === 'number'
          ? typeValue
          : typeValue !== null && typeValue !== undefined
            ? Number(typeValue)
            : null;
        const amount = numericPrice * quantity;

        totalQuantity += quantity;
        totalSoundWave += amount;

        const giftId = (record.get('giftId') as string | null) ?? giftModel?.get('id') ?? null;
        const key = giftId ?? `unknown-${giftModel?.get('name') ?? ''}`;

        if (!breakdownMap.has(key)) {
          breakdownMap.set(key, {
            giftId,
            name: (giftModel?.get('name') as string) || '未知礼物',
            quantity: 0,
            price: numericPrice,
            amount: 0,
            icon: (giftModel?.get('icon') as string) ?? null,
            type: normalizedType,
          });
        }

        const item = breakdownMap.get(key)!;
        item.quantity += quantity;
        item.amount += amount;
      }

      const breakdown = Array.from(breakdownMap.values()).sort((a, b) => b.amount - a.amount);

      return {
        totalRecords: giftRecords.length,
        totalQuantity,
        totalGiftTypes: breakdown.length,
        totalSoundWave,
        uniqueUsers: uniqueUsers.size,
        breakdown,
      };
    } catch (error) {
      console.error('❌ 获取场次礼物统计失败:', error);
      throw error;
    }
  }
}
